import React, { Component,Fragment } from 'react';
import router from 'umi/router';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormattedMessage, formatMessage } from 'umi/locale';
import style from './menu.less';
import { useNoRoutePermisstion,usePlatform } from '@/defaultSettings.js';
import CustomModal from './Modal.js';
import NoRoutePermisstionModal from './NoRoutePermisstionModal.js';
import {
    Input,
    DatePicker,
    Form,
    Row,
    Tooltip,
    Col,
    Divider,
    Card,
    Tabs,
    PageHeader,
    Alert,
    message,
    Icon,
    Tree,
} from 'antd';
import {Select,Button , Table ,Modal,Pagination} from '@/components/CustomAntd'

const { TabPane } = Tabs;
//表单
const FormItem = Form.Item;
//多级选择树
const TreeNode = Tree.TreeNode;


const parmsForTabs = {
  type_route : {
    is_left_menu:'1,4',
  },
  type_component :{
    is_left_menu:'2,3',
  }
}

@connect(({ permission_management, loading }) => ({
    permission_management,
    loading: loading.models.permission_management,
}))
@Form.create()
class List extends Component {
  state={selectId:"",platformType:""}

    componentDidMount() {

        const { dispatch , permission_management: { selectedTab }} = this.props;
        dispatch({
            type: "permission_management/fetch",
            payload: {
              ...parmsForTabs[selectedTab],
            },
        })
    }
    componentWillUnmount() {//页面退出时的生命周期
      const { dispatch,form:{resetFields}} = this.props;
      dispatch({
        type: 'permission_management/save',
        payload: {
            modalVisible: false,
            treeList: [],
            platformtnameList:[],
            permission_name: '',    //菜单名称
            permission_id: '',      //菜单id
            route: '',              //菜单路径
            seq: '',                //菜单顺序
            per_id:'',
            updateData: {},
            is_left_menu:'',
            platform_type:'',
            selectedTab : 'type_route'
        },
      })
    }
    renderTreeNodes = treeList => treeList.map((item) => {
      let permission_name = '';
      if(item.permission_name && item.permission_name.length < 20){
        permission_name= item.permission_name
      } else {
        permission_name= item.permission_name.split(0,20) + '...'
      }
        if (item.permissions) {
            return (
                <TreeNode title={permission_name} key={item.permission_id} dataRef={item} value={item.permission_id}>
                    {this.renderTreeNodes(item.permissions)}
                </TreeNode>
            );
        } else {
            return (
                <TreeNode
                  title={permission_name}
                  key={item.permission_id}
                  dataRef={item} value={item.permission_id}>
                </TreeNode>
            );
        }
    })

    //选中树时的方法
    treeNow = (selectedKeys, e) => {
      this.state.selectId = selectedKeys;
        const { permission_management, dispatch } = this.props;
        let { permission_name, permission_id, seq, route,is_left_menu,platform_type} = permission_management;
        //选中树的时候初始值存入states
        if(e.selected){
          dispatch({
            type: 'permission_management/save',
            payload: {
              permission_name: e.node.props.dataRef.permission_name,
              permission_pid: e.node.props.dataRef.permission_pid,   //父级id
              permission_id :e.node.props.dataRef.permission_id,     //本身的id
              per_id: e.node.props.value,
              seq: e.node.props.dataRef.seq,
              route: e.node.props.dataRef.route,
              is_left_menu:e.node.props.dataRef.is_left_menu,
              platform_type:e.node.props.dataRef.platform_type,
              treeAll:e.node.props.dataRef,
            }
          })
        }else {
          dispatch({
            type: 'permission_management/save',
            payload: {
              permission_name: undefined,    //菜单名称
              permission_id: undefined,      //菜单id
              route: undefined,              //菜单路径
              seq: undefined,                //菜单顺序
            }
          })
        }


    }

    //新增修改
    changeFlag = (modalType) => {
        const { permission_management, dispatch } = this.props;
        let { permission_name, permission_id, seq, route,is_left_menu,platform_type,per_id,modalVisible} = permission_management;
        if(modalType != 'father'){
            if (!permission_id || permission_id === '') {
                message.error('必须选择一个左侧菜单才能继续操作！');
                return false;
            }
        }
        if (modalType === 'father') {
            dispatch({
                type: 'permission_management/save',
                payload: {
                    modalType: modalType,
                    modalVisible: true,
                },
            })
        }else if (modalType === 'brother') {
            dispatch({
                type: 'permission_management/save',
                payload: {
                    modalType: modalType,
                    modalVisible: true,
                },
            })
        } else if (modalType === 'children') {
            dispatch({
                type: 'permission_management/save',
                payload: {
                    modalType: modalType,
                    modalVisible: true,

                },
            })
        } else if (modalType === 'edit') {
            dispatch({
                type: 'permission_management/detail',
                payload: {
                    modalType: modalType,
                    modalVisible: true,
                    per_id:per_id,

                },

            })
        }
    }


    //刷新重载
    reload = () => {
        const { form: { getFieldsValue }, permission_management: { selectedTab }, dispatch } = this.props;
        let fields = getFieldsValue();
        const params = {
          platform_type:this.state.platformType ? this.state.platformType : "",
          ...parmsForTabs[selectedTab],
        };

        dispatch({
            type: 'permission_management/fetch',
            payload: params,
        })


    }

    //模态框取消
    modalHandleCancel = () => {
        const { dispatch } = this.props
        dispatch({
            type: 'permission_management/save',
            payload: {
                modalVisible: false,

            }
        })
    }

    //确认按钮
    modalHandleOk = (subFields, e) => {
        const { dispatch, form, permission_management } = this.props;
        let { per_id,permission_pid,updateData } = permission_management;
        form.resetFields();
        if (subFields.modalType === 'father') {
            dispatch({
                type: 'permission_management/create',
                payload: {
                    ...subFields,
                }

            }).then((r) => {
                if (r == true) {
                    this.reload();
                    dispatch({
                        type: 'permission_management/save',
                        payload: {
                            modalVisible: false,
                        }
                    })
                }else{
					dispatch({
					    type: 'permission_management/save',
					    payload: {
					        modalVisible: true,
					    }
					})
				}
            });
        } else if (subFields.modalType === 'brother') {
            dispatch({
                type: 'permission_management/create',
                payload: {
                    ...subFields,
                  permission_pid: permission_pid
                }

            }).then((r) => {
                if (r) {
                    this.reload();
                    dispatch({
                        type: 'permission_management/save',
                        payload: {
                            modalVisible: false,
                        }
                    })
                }
            });


        } else if (subFields.modalType === 'children') {
            dispatch({
                type: 'permission_management/create',
                payload: {
                    ...subFields,
                    permission_pid: per_id
                }
            }).then((r) => {
                if (r) {
                    this.reload();
                    dispatch({
                        type: 'permission_management/save',
                        payload: {
                            modalVisible: false,

                        }
                    })
                }
            });
        } else if (subFields.modalType === 'edit') {
            dispatch({
                type: 'permission_management/update',
                payload: {
                  ...subFields,
                },


            }).then((r) => {
                if (r == true) {
                    this.reload();
                    dispatch({
                        type: 'permission_management/save',
                        payload: {
                            modalVisible: false,
                            permission_name:subFields.permission_name,
                            permission_id: subFields.permission_id,
                            seq:subFields.seq,
                            route: subFields.route,
                            is_left_menu:subFields.is_left_menu,
                            platform_type:subFields.platform_type,
                            icon:subFields.icon,
                        }
                    })
                }else{
					dispatch({
					    type: 'permission_management/save',
					    payload: {
					        modalVisible: true,
					        permission_name:subFields.permission_name,
					        permission_id: subFields.permission_id,
					        seq:subFields.seq,
					        route: subFields.route,
					        is_left_menu:subFields.is_left_menu,
					        platform_type:subFields.platform_type,
					        icon:subFields.icon,
					    }
					})
				}
            });
        }


    }

    //删除
    deleteList = (id) => {
        const { dispatch, form, permission_management } = this.props;
        let { permission_id } = permission_management;
        const reload = () => {
            this.reload();
        }
        if (id === '' ||  permission_id == undefined) {
            message.error('必须选择一个左侧菜单才能删除哦！');
            return false;
        }
        Modal.confirm({
        okText: "确定",
        cancelText: "取消",
              title: '确认删除吗',
              content: '您确定要删除这条数据吗？',
              onOk() {
                  //发送删除请求

                  dispatch({
                      type: 'permission_management/delete',
                      payload: {
                          permission_id: id
                      },
                  }).then((r) => {
                      if (r) {
                          reload();
                        dispatch({
                          type: 'permission_management/save',
                          payload: {
                            permission_name: undefined,    //菜单名称
                            permission_id: undefined,      //菜单id
                            route: undefined,              //菜单路径
                            seq: undefined,                //菜单顺序
                          }
                        })
                      }
                  })
              },
              onCancel() {
                  return false;
              },
          })
    };
    handleFormReset = () => {
      const { form, dispatch } = this.props;
      form.resetFields();
    };




    handleSearch = e => {
      e.preventDefault();
      const { dispatch, form ,permission_management: { selectedTab } } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        let fields = fieldsValue;
        if(selectedTab === 'type_route'){
          dispatch({
            type: "permission_management/searchTree",
            payload: {
              ...fields ,
              ...parmsForTabs[selectedTab],
            },
          }).then((r)=>{
            dispatch({
              type: "permission_management/save",
              payload: {
                selectedTab :selectedTab,
              },
            })
          })
        }else if(selectedTab === 'type_component'){
          dispatch({
            type: "permission_management/searchList",
            payload: {
              ...fields ,
              ...parmsForTabs[selectedTab],
            },
          }).then((r)=>{
            dispatch({
              type: "permission_management/save",
              payload: {
                selectedTab :selectedTab,
              },
            })
          })
        }
      })
    };
    showNoRouteModal = (modalType, data) => {
      const { dispatch ,permission_management :{} } = this.props
      if (modalType === 'create') {
          dispatch({
              type: "permission_management/noRouteTypeChange",
              payload: {
                  is_left_menu:'1,4',
              },
          }).then(()=>{
              dispatch({
                  type: 'permission_management/save',
                  payload: {
                      noRouteModalVisible: true,
                      noRouteModalType: modalType,
                  }
              })
          })

      }else if (modalType === 'edit'){
        dispatch({
          type: 'permission_management/showNoRouteModalForUpdate',
          payload: {
            modalType: modalType,
            per_id :data.permission_id
          }
        })
      }
    }
    platChange =(value)=> {
      this.setState({
        platformType : value,
      });

    };
    tabChange = (key)=>{ //type_component  type_route
        const { dispatch, form:{getFieldsValue},permission_management: { selectedTab } } = this.props;
        if(key === 'type_route'){
          let fields = getFieldsValue();
          dispatch({
            type: "permission_management/searchTree",
            payload: {
              ...fields ,
              ...parmsForTabs[key],
            },
          }).then((r)=>{
            dispatch({
              type: "permission_management/save",
              payload: {
                selectedTab :key,
              },
            })
          })
        }else if(key === 'type_component'){
          let fields = getFieldsValue();
          dispatch({
            type: "permission_management/searchList",
            payload: {
              ...fields ,
              ...parmsForTabs[key],
            },
          }).then((r)=>{
            dispatch({
              type: "permission_management/save",
              payload: {
                selectedTab :key,
              },
            })
          })
        }
    }
    //模态框取消 非页面功能
    noRouteModalHandleCancel = () => {
      const { dispatch } = this.props
      dispatch({
        type: 'permission_management/save',
        payload: {
          noRouteModalVisible: false,

        }
      })
    }
    //确认按钮  非页面功能
    noRouteModalHandleOk = (subFields, e) => {
      const { dispatch, form :{fieldsValue},permission_management: { selectedTab,noRouteModalType } } = this.props;
      if (noRouteModalType === 'create') {
        dispatch({
          type: 'permission_management/create',
          payload: {
            ...subFields,
          }
        }).then((r) => {

          if (r == true) {
            dispatch({
              type: 'permission_management/searchList',
              payload: {
                ...fieldsValue,
                ...parmsForTabs[selectedTab],
              }
            })
            dispatch({
              type: 'permission_management/save',
              payload: {
                noRouteModalVisible: false,
              }
            })
          }
        });
      }else if (noRouteModalType == 'edit'){
        dispatch({
          type: 'permission_management/update',
          payload: {
            ...subFields,
          }
        }).then((r) => {
          if (r == true) {
            dispatch({
              type: 'permission_management/searchList',
              payload: {
                ...fieldsValue,
                ...parmsForTabs[selectedTab],
              }
            })
            dispatch({
              type: 'permission_management/save',
              payload: {
                noRouteModalVisible: false,
              }
            })
          }
        });
      }
    }
  //删除
  noRoutedeleteList = (id) => {
    const { dispatch, form :{getFieldsValue}, permission_management } = this.props;
    let { selectedTab} = permission_management;
    let fields = getFieldsValue();
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      onOk() {
        //发送删除请求

        dispatch({
          type: 'permission_management/delete',
          payload: {
            permission_id: id
          },
        }).then((r) => {
          if (r) {
            dispatch({
              type: "permission_management/searchList",
              payload: {
                ...fields ,
                ...parmsForTabs[selectedTab],
              },
            }).then((r)=>{
              dispatch({
                type: "permission_management/save",
                payload: {
                  selectedTab :selectedTab,
                },
              })
            })
          }
        })
      },
      onCancel() {
        return false;
      },
    })
  };

    renderSimpleForm() {
      const { getFieldDecorator } = this.props.form;
      const { permission_management: { platformtnameSeach,platformtnameList,selectedTab  } } = this.props;

      return (
        <Form onSubmit={this.handleSearch} layout="inline">
          <div
            style={{
              fontSize: '16px',
              marginBottom: '15px',
            }}
          >
            <div style={{ height: 60 }}>
              {/* 我将所有的 搜索框都放到 一个div 和一个 row里了  所以这个100的高度是两排按钮的情况 如果你有三排按钮 就得设置成150高度*/}
              <Row align="middle">
                <Col xl={2} lg={12} sm={24}/>
                  {
                      usePlatform?
                          <Col xl={8} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                              <div style={{ marginTop: '2px',marginLeft : '15px', marginRight: '20px', display: 'inline-block' }}>平台类型 :</div>
                              {getFieldDecorator('platform_type',)(
                                  <Select placeholder="请选择" style={{ width: '65%' }} allowClear={true} onChange={this.platChange}>
                                      {platformtnameSeach && platformtnameSeach.length > 0 ?
                                          platformtnameSeach.map(function(item) {
                                              return <Select.Option key={item.k} id={item.k}
                                                                    value={item.k}>{item.v}
                                              </Select.Option>;
                                          }) : []
                                      }
                                  </Select>
                              )}
                          </Col> :
                          <Col xl={8} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                              <div style={{ marginTop: '2px',marginLeft : '15px', marginRight: '20px', display: 'inline-block' }}>平台名称 :</div>
                              {getFieldDecorator('permission_name',)(
                                  <Input style={{  width: '65%'  }} placeholder="请输入" />
                              )}
                          </Col>
                  }


                <Col  xl={12} lg={12} sm={24} style={{ marginTop: 13 }}>
                  <span>
                    {
                      selectedTab === 'type_component' ?
                      <Button
                        type="primary"
                        onClick={() => {
                          this.showNoRouteModal('create');
                        }}
                      >
                        新建
                      </Button> :[]
                    }
                    <span>
                      <Button style={{ marginLeft: 8 }}  type="primary" htmlType="submit">
                        查询
                      </Button>
                      <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                        重置
                      </Button>
                    </span>
                  </span>
                </Col>
              </Row>
            </div>
          </div>
        </Form>
          )
    };
    //渲染DOM
    render() {


        const { permission_management:
          {
            modalVisible, modalType, treeList, permission_name, permission_pid,per_id, sep, route, updateData,platformtnameList ,selectedTab ,permissionList,

            noRouteModalType,
            noRouteUpdateData,
            noRouteModalVisible

          } } = this.props

        const typesList = {
          type_route : [
            {
              k: '1',
              v: '左菜单页面'
            },
            {
              k: '4',
              v: '非左菜单页面'
            },
          ],
          type_component :[
            {
              k: '2',
              v: '非左菜单功能'
            },
            {
              k: '3',
              v: formatMessage({ id: 'iot.app.system.other.platform'})
            }
          ]
        }
        const columns = [
          {
            title: '功能名称',
            align: 'center',
            dataIndex: 'permission_name',
            key: 'permission_name',

          },
          {
            title: <div>功能标识/url路径 <Tooltip  placement="right" title= {<div ><div>标识 : 功能的唯一标识，由开发人员提供。</div><div>url路径 : 第三方平台的访问路径</div></div>}><Icon type="question-circle" /></Tooltip></div>,
            align: 'center',
            dataIndex: 'route',
            key: 'route',
          },
          {
            title: '功能类型',
            align: 'center',
            key: 'is_left_menu',
            render: (text, record) => {
              if (record.is_left_menu ) {
                let content = '';
                switch (record.is_left_menu){
                  case '2':
                    content = '页面内功能';
                    break ;
                  case '3':
                    content = '第三方平台'
                    break ;
                }
                return (
                  <div >
                    {content}
                  </div>
                )
              }
              return '';
            }
          },
          {
            title: '所属页面',
            align: 'center',
            key: 'p_id',
            render: (text, record) => {
              if (record.permissions  ) {
                  return (
                    <div >
                      {record.permissions[0]?record.permissions[0].permission_name:''}
                    </div>
                  )
              }
              return '';
            }
          },

        usePlatform ?{
                    title: '所属平台',
                    align: 'center',
                    key: 'platform_type',

                    render: (text, record) => {
                        let content = '';
                        if (record.platform_type) {
                            let platform =  record.platform_type.indexOf(',')!= -1 ? record.platform_type.split(",").slice(0,-1):[record.platform_type] ;
                            if(platformtnameList && platformtnameList.length > 0 && platform && platform.length >0){
                                platformtnameList.map((item,key)=>{
                                    platform.map((plat,key2)=>{
                                        if(plat === item.k){
                                            content = content + item.v +','
                                        }
                                    })
                                })
                                /*if (content.length>0) {
                                  content.substring(0,content.Length-1)
                                }*/
                            }
                        }
                        return (
                            <div>
                                {content}
                            </div>
                        )
                    }
                } : {width :0},

          {
            title: '操作',
            fixed: 'right',
            width: 150,
            render: (text, record) => (
              <Fragment>
                <a onClick={e => this.showNoRouteModal('edit', record)}>编辑</a>
                <Divider type="vertical" />
                <a  onClick={(e) => this.noRoutedeleteList(record.permission_id)}>删除</a>
              </Fragment>
            ),
            align: 'center',
          },
        ]
        let treeShow = (
            <div>
                <p className={style.p1}>已有功能如下：</p>
                <Tree className={style['input-box']} showLine={true} onSelect={this.treeNow} defaultExpandParent>
                    {treeList && treeList.length>0?this.renderTreeNodes(treeList):[]}
                </Tree>
            </div>
        );
        return (
            <div>
                <PageHeaderWrapper>
                    <div className={style.box}
                        style={{
                            backgroundColor: "#FFFFFF",
                            paddingLeft: "2%",
                            paddingRight: "5%",
                            paddingTop : '1%',
                            paddingBottom : '1%',
                        }}
                    >
                        {this.renderSimpleForm()}
                        <Tabs tabPosition='left' activeKey = {selectedTab} onChange={this.tabChange}>
                          <TabPane tab="页面功能" key="type_route">

                            <Row gutter={16}>
                              <Col span={8}>
                                  {treeShow}
                              </Col>
                              <Col span={16}>
                                <Card className={style['show-box']}>
                                  <div className={style['show-one-block']}>
                                    <p className={style.p2}>
                                      当前选中：
                                    </p>
                                    <Input className={style['show-input']} value={permission_name} disabled />
                                  </div>
                                  <div className={style['but-box']}>
                                    <Button className={style.butt} onClick={() => this.changeFlag('brother')}>新增同级页面</Button>
                                    {
                                      permission_pid?
                                        <Button className={style.butt} disabled={true} onClick={() => this.changeFlag('children')}>新增子级页面</Button>
                                        :
                                        <Button className={style.butt} onClick={() => this.changeFlag('children')}>新增子级页面</Button>
                                    }
                                    <Button className={style.butt} onClick={() => this.changeFlag('father')}>新增根节点</Button>

                                  </div>
                                  <div className={style['but-box']}>
                                    <Button className={style.butt} onClick={() => this.changeFlag('edit')}>修改页面信息</Button>
                                    <Button className={style.butt} type="danger" onClick={() => this.deleteList(per_id)}>删除页面</Button>
                                  </div>
                                </Card>
                              </Col>
                            </Row>
                          </TabPane>

                            {
                                useNoRoutePermisstion ?
                                    <TabPane tab="非页面功能" key="type_component">
                                        <Table
                                            scroll={{ x: 1200 }}
                                            pagination={false}
                                            columns={columns}
                                            dataSource={permissionList}
                                            rowKey={record => record.permission_id}
                                        />
                                    </TabPane>
                                    :
                                    []
                            }


                        </Tabs>



                        {
                          noRouteModalVisible ?
                            <NoRoutePermisstionModal
                                modalType={noRouteModalType}
                                visible={noRouteModalVisible}
                                updateData={noRouteUpdateData}
                                modalHandleCancel={this.noRouteModalHandleCancel}
                                modalHandleOk={this.noRouteModalHandleOk}
                                typesList={typesList[selectedTab]}
                                platformtnameList={platformtnameList}
                            />
                            :
                            []
                        }


                        {modalVisible ?
                            <CustomModal
                                modalType={modalType}
                                visible={modalVisible}
                                selectId={this.state.selectId}
                                updateData={updateData}
                                modalHandleCancel={this.modalHandleCancel}
                                modalHandleOk={this.modalHandleOk}
                                typesList={typesList[selectedTab]}
                                platformtnameList={platformtnameList}
                            />
                            : []
                        }
                    </div>
                </PageHeaderWrapper>
            </div>
        );
    }
};























export default List;







